#include <stdio.h>
#include <memory>

#include "bike.pb.h"
#include "logger.h"
#include "bksevent.h"
#include "event_def.h"
#include "userhandler.h"
#include "dispatchtaskservice.h"
#include "networkinterface.h"
#include "iniconfig.h"
#include "businessprocesser.h"
#include "sqlconn_pool.h"

#define LOG_FILE_PATH "../conf/log.conf"

using namespace tutorial;

int main(int argc, char ** argv){

    if(-1 == Logger::getInstance()->init(LOG_FILE_PATH))
    {
        printf("Main ---> Logger init failed.\n");
        return -1;
    }

    std::shared_ptr<IniConfig> ini_ptr = std::make_shared<IniConfig>();
    if(!ini_ptr->loadfile("../conf/shared_bike.ini")){
        LOG_ERROR("Main ---> can not load ../conf/shared_bike.ini");
    }
    // mobile_request mreq;
    // mreq.set_mobile("18136728538");

    // printf("mobile: %s\n", mreq.mobile().c_str());

    // MobileCodeReqEv *reqev = new MobileCodeReqEv("18136728538");

    // reqev->dump(std::cout); 

    // auto rspev = hand.handle(reqev);

    // rspev->dump(std::cout);
    // DispatchTaskService *_DTS = NULL;
    // _DTS = DispatchTaskService::getInstance();

    // if(_DTS->open())
    // {
    //     LOG_DEBUG("DispatchTaskService::open ---> thread_pool start working ...");
    // }
    // else{
    //     LOG_WARN("DispatchTaskService::open ---> open failed.");
    //     return -1;
    // }

    // _DTS->enqueue(reqev);
    auto _config = ini_ptr->getconfig();
    unsigned short server_port = _config.server_port;
    LOG_INFO("Main ---> server_port:%d", _config.server_port);
    std::shared_ptr<ConnPool> _pool = std::make_shared<ConnPool>();
    std::shared_ptr<BusinessProcesser> busprocesser = std::make_shared<BusinessProcesser>(_pool);
    // UserHandler hand;
    busprocesser->init();
    
    NetWorkInterface *worker = new NetWorkInterface();

    if(!worker->start(server_port)){
        LOG_DEBUG("NetWorkInterface::start ---> NetworkInterface start failed.");
        return -1;
    }
    LOG_DEBUG("NetWorkInterface::start ---> NetworkInterface start success.");

    while(1){
        worker->network_event_dispatch();
        LOG_DEBUG("NetWorkInterface::network_event_dispatch ---> waiting ...");
        sleep(1);
    }

    worker->stop();

    return 0;
}
